package com.cci.kangdao.utilTool;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.config.EmailConfiguration;
import com.cci.kangdao.dao.DictionariesTDao;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件工具类------主要为工单报警机制使用，不作为其他使用；邮箱的参数从  Dictionaries_T 表中获取  DTableName='emailReminder'，DTableName='emailReminderChannel'，
 *
 * @author Eric
 */
@Component
public class MailUtilException {

    private static String starttlsEnable;

    private static String enablePort = "false";

    @Resource
    public DictionariesTDao dictionariesTDao;

    private static MailUtilException mailUtilException;

    private static Logger log = Logger.getLogger(MailUtilException.class);

    @PostConstruct
    public void init() {
        mailUtilException = this;
        mailUtilException.dictionariesTDao = this.dictionariesTDao;    //改成你们对应的Dao层
    }

    public static void set(String starttlsEnable, String enablePort) {
        MailUtilException.starttlsEnable = starttlsEnable;
        MailUtilException.enablePort = enablePort;

    }

    //获取表中的数据
    public static EmailConfiguration getEmailData() {
        String emailReminder = mailUtilException.dictionariesTDao.getListByDTableName("emailReminder");
        EmailConfiguration emailConfiguration = null;
        if (StringUtils.isNotBlank(emailReminder)) {
            List<String> allowProvinceList = JSON.parseArray(emailReminder, String.class);
            if (CollectionUtils.isNotEmpty(allowProvinceList)) {
                //["smtp-mail.outlook.com","587","e_cummins@outlook.com","Cummins123","25000","e_cummins@outlook.com","true"]
                emailConfiguration = new EmailConfiguration();
                emailConfiguration.setHost(allowProvinceList.get(0));
                emailConfiguration.setPort(allowProvinceList.get(1));
                emailConfiguration.setUsername(allowProvinceList.get(2));
                emailConfiguration.setPassword(allowProvinceList.get(3));
                emailConfiguration.setTimeout(allowProvinceList.get(4));
                emailConfiguration.setFrom(allowProvinceList.get(5));
                emailConfiguration.setStarttlsEnable(allowProvinceList.get(6));
            }
        }
        return emailConfiguration;
    }


    /**
     * 创建邮件发送器
     *
     * @return
     */
    private static JavaMailSenderImpl createMailSender() {

        EmailConfiguration emailConfiguration = getEmailData();

        String host = emailConfiguration.getHost();
        String port = emailConfiguration.getPort();
        String username = emailConfiguration.getUsername();
        String password = emailConfiguration.getPassword();
        String timeout = emailConfiguration.getTimeout();

        if (StringUtils.isEmpty(starttlsEnable)) {
            starttlsEnable = emailConfiguration.getStarttlsEnable();
        }

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(host);
        sender.setPort(Integer.parseInt(port));
        sender.setUsername(username);
        sender.setPassword(password);
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.put("mail.smtp.connectiontimeout", timeout);// 设置接收超时时间
        p.put("mail.smtp.writetimeout", timeout);
        p.setProperty("mail.smtp.timeout", timeout);
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.starttls.enable", starttlsEnable);
        p.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
        if (enablePort.matches("^(true)$")) {
            p.put("mail.smtp.ssl.trust", port);
        }

        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 发送邮件 自己给自己发送
     *
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendMail(String subject, String content, String channel) {
        String emailReminderFlag = mailUtilException.dictionariesTDao.getListByDTableName("emailReminderFlag");
        String emailReminderChannel = mailUtilException.dictionariesTDao.getListByDTableName("emailReminderChannel");
        if (StringUtils.isNotBlank(emailReminderChannel)) {
            List<String> emailReminderChannelList = JSON.parseArray(emailReminderChannel, String.class);
            if (StringUtils.isNotBlank(emailReminderFlag) && Boolean.valueOf(emailReminderFlag) && emailReminderChannelList.contains(channel)) {
                try {
                    EmailConfiguration emailConfiguration = getEmailData();
//                    log.error(emailConfiguration.toString());
                    if (null == emailConfiguration) {
                        return;
                    }
                    String from = emailConfiguration.getFrom();
                    //获取接收人的邮箱
                    List<Map<String,Object>> receiveList = mailUtilException.dictionariesTDao.getDictionariesListByDTableName("emailReceive");
                    for(Map<String,Object> emailReceive : receiveList){
                        JavaMailSenderImpl mailSender = createMailSender();
                        MimeMessage mimeMessage = mailSender.createMimeMessage();
                        // 设置utf-8或GBK编码，否则邮件会有乱码
                        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                        messageHelper.setFrom(from);
                        messageHelper.setTo(MapUtils.getString(emailReceive,"DValue"));
                        messageHelper.setSubject(channel + ":" + subject);
                        messageHelper.setText(content, true);
                        mailSender.send(mimeMessage);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    }


}
